package com.gagakuai.bpm.mqlistener.camunda.handler.returns;

import com.alibaba.fastjson.JSON;
import com.gagakuai.bpm.common.component.SpringContextHolder;
import com.gagakuai.bpm.common.enums.BusinessCodeEnum;
import com.gagakuai.bpm.common.exception.BpmException;
import com.gagakuai.bpm.domian.entity.camuda.ActHiComment;
import com.gagakuai.bpm.mqlistener.camunda.baseproxy.BaseConsumer;
import com.gagakuai.bpm.service.camunda.WorkflowTaskService;
import com.gagakuai.bpm.utils.AssertUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Objects;

/*
 * @program: mss_server
 * @description: bpm流程退回第一步 (取消重填)
 * @author: houhong
 * @create: 2022-04-06 10:59
 */
@Component
@Slf4j
public class BpmWithReturnStepConsumer implements BaseConsumer {


    @Autowired
    private WorkflowTaskService workflowTaskService;

  /*  @Qualifier("transactionManager")
    @Autowired
    private DataSourceTransactionManager transactionManager;*/

    @Autowired
    private PlatformTransactionManager transactionManager;

    /*
     * @param message 消息
     * @param channel 通道
     * @return
     * @Author houhong
     * @Description //TODO  取回消费者
     * @Date 11:00 上午 2022/3/25
     */
    @Override
    public void consume(Message message, Channel channel, String messageType) throws Exception {


        if (Objects.isNull(transactionManager)) {

            transactionManager = (DataSourceTransactionManager) SpringContextHolder.getBean("transactionManager");
        }

        log.info("=============进行取回实际处理节点================");
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            String str = new String(message.getBody());
            ActHiComment actHiComment = JSON.parseObject(str, ActHiComment.class);


            int reslut = workflowTaskService.processReturn(actHiComment.getProcInstId(), actHiComment);
            //断言处理结果
            AssertUtils.assertRetunTrue(reslut);

            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw new BpmException(BusinessCodeEnum.BPM_RETURN_LAST_STEP_FAILED);
        } finally {
            //todo 做点什么呢
        }

        log.info("===================进行取回实际处理成功==========================");

    }


}